from qgis.core import *
from qgis.gui import *

from PyQt4.QtGui import *
from PyQt4.QtCore import *

def getData(layer,names,all=False,points=False):
    """ return xy point coords and attribute data. If all=True then ignore current selection """
    if points:
        x=[]
        y=[]
    # initialise return dict:
    data={}
    for z in names:
        data[z]=[]
    provider=layer.dataProvider()
    indexes = [provider.fieldNameIndex(i) for i in names]
    if layer.selectedFeatureCount() > 0 and not all:
        fids = layer.selectedFeaturesIds()
    else:
        fids = range(layer.featureCount())

    for fid in fids:
        feat = QgsFeature()
        provider.featureAtId(fid,feat,True,indexes)
        atts = feat.attributeMap()
        getTypedFields(atts,provider.fields())
        for iname in zip(indexes,names):
            data[iname[1]].append(atts[iname[0]])
        if points:
            xy=feat.geometry().asPoint()
            x.append(xy[0])
            y.append(xy[1])
        
    result = {'attributes': data}
    if points:
        result['x']=x
        result['y']=y
    return result

def getTypedFields(attributeMap,fields):
    for k,v in attributeMap.items():
        typeName = fields[k].typeName()
        if typeName == 'Integer':
            v=v.toInt()[0]
        elif typeName == 'Real':
            v=v.toDouble()[0]
        else:
            v=str(v.toString())
        attributeMap[k]=v

def getDouble(layer,name):
    """ get attribute 'name' from layer as floating point value """
    return [x[0] for x in _getAttr(layer,name,"toDouble")]

def getInt(layer,name):
    """ get attribute 'name' from layer as integer value """
    return [x[0] for x in _getAttr(layer,name,"toInt")]

def getQString(layer,name):
    """ get attribute 'name' from layer as QString """
    return _getAttr(layer,name,"toString")

def getString(layer,name):
    """ get attribute 'name' from layer as python string """
    return [str(x) for x in getQString(layer,name)]


def _getAttr(layer,name,attr):
    """ get attribute 'name' from layer, converting the resultant QVariant 
    by applying the 'attr' method """
    data = []
    provider = layer.dataProvider()
    index = provider.fieldNameIndex(name)
    if layer.selectedFeatureCount() > 0:
        features = layer.selectedFeatures()
        [data.append(getattr(x.attributeMap()[index],attr)()) for x in features]
    else:
        for featureId in range(provider.featureCount()):
            feat = QgsFeature()
            provider.featureAtId(featureId,feat,True,[index])
            data.append(getattr(feat.attributeMap()[index],attr)())
    return data
        
